package com.ciwong.epaper.modules.me.i;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public abstract class OnLoadMoreListener extends RecyclerView.OnScrollListener {
    private LinearLayoutManager layoutManager;
    private int totalItemCount, lastPosition, lastItemCount;
    boolean isToLast = false;//判断是否是垂直向下方向滑动

    public abstract void onLoadMore();

    public abstract void onUnLoadMore();

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            totalItemCount = layoutManager.getItemCount();
            lastPosition = layoutManager.findLastCompletelyVisibleItemPosition();//从0开始
        } else {
            return;
        }
        if (isToLast && lastPosition == totalItemCount - 1) {
            this.onLoadMore();
        } else {
            // 当不滚动时(看需求，滚动的时候也可以加上)
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                this.onUnLoadMore();
            }
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        if (dy > 0) {
            isToLast = true;
        }
    }
}